import { _decorator, Component, Label, Node, Slider } from 'cc';
import { DevelopState, Soldier } from '../entity/Soldier';
import VillageApi from '../api/VillageApi';
import { UIManager } from '../common/UIManager';
import { UserInfo } from '../common/UserInfo';
import { PrefabEnum } from '../common/PrefabEnum';
import { EventManager } from '../event/EventManager';
import { TrainIndex } from './TrainIndex';
import { TrainTabType } from '../entity/TrainTabType';
import { Utils } from '../common/Utils';
import { TrainProperty } from './TrainProperty';
import { Events } from '../entity/Events';
import { EventOper } from '../entity/Buildings';
import { buildingType } from '../settings/const';
import { BManager } from '../entity/BManager';
const { ccclass, property } = _decorator;

@ccclass('TrainNumber')
export class TrainNumber extends Component {
    @property(Node)
    bg: Node
    @property(Node)
    proBtn: Node
    @property(Node)
    close: Node

    @property(Label)
    soldierName: Label
    @property(Label)
    food: Label
    @property(Label)
    wood: Label
    @property(Label)
    mud: Label
    @property(Label)
    iron: Label
    @property(Label)
    time: Label

    @property(Label)
    count: Label
    @property(Label)
    trainCount: Label
    @property(Slider)
    slider: Slider
    @property(Label)
    sliderCount: Label

    @property(Label)
    trainNum: Label
    @property(Label)
    timeDown: Label
    @property(Node)
    numNode: Node
    @property(Node)
    timeNode: Node

    @property(Node)
    comfirm: Node
    @property(Node)
    canNot: Node
    @property(Label)
    canNotLabel: Label
    @property(Node)
    speed: Node
    @property(Node)
    develop: Node

    soldierData: Soldier

    _maxCount: number = 0
    _curTrainCount: number = 0

    offsetTime: number = 0

    start() {
        this.close.on(Node.EventType.TOUCH_END, this.onClose, this)
        this.proBtn.on(Node.EventType.TOUCH_END, this.onPro, this)

        this.comfirm.on(Node.EventType.TOUCH_END, this.onComfrim, this)
        this.speed.on(Node.EventType.TOUCH_END, this.onSpeed, this)
        this.develop.on(Node.EventType.TOUCH_END, this.onDevelop, this)



        this.slider.node.on('slide', this.onSlide, this);
    }

    setData(soldier: Soldier) {
        this.soldierData = soldier
        this.soldierName.string = soldier.name

        this.food.string = this.soldierData.food + ''
        this.wood.string = this.soldierData.wood + ''
        this.mud.string = this.soldierData.mud + ''
        this.iron.string = this.soldierData.iron + ''
        this.time.string = Utils.secondToStr(this.soldierData.trainTime)

        this.count.string = soldier.count + ''

        this._maxCount = soldier.canCreateHowMany()
        this.sliderCount.string = this._maxCount + ''

        let eventList = Soldier.getAllTrainEvent()
        // 判断是在兵营里，还是在宫殿
        // if(UIManager.instance.isOpenUI(PrefabEnum.TrainIndex)){
        //     eventList = Soldier.getBarracksTrainEvent()
        // } else {
        //     eventList = Soldier.getPalaceTrainEvent()
        // }
        if (eventList.length > 0) {
            let event = soldier.getTrainEvent()

            if (event) {
                this.timeNode.position = this.numNode.position
                this.speed.position = this.comfirm.position
                this.numNode.active = false
                this.comfirm.active = false
                this.countDown(event)
            } else {
                let arr = eventList[0].eParam.split(',')
                let id = arr[0]
                this.numNode.active = false
                this.comfirm.active = false
                this.canNot.position = this.comfirm.position
                this.canNotLabel.string = Soldier.createById(parseInt(id)).name + '训练中'
            }
        }

        if (this.soldierData.developed != DevelopState.Developed) {
            this.numNode.active = false
            this.comfirm.active = false
            this.develop.position = this.comfirm.position

        }

    }

    countDown(event: Events) {
        this.unschedule(this.updateTime)
        if (!event) {
            return
        }

        let arr = event.eParam.split(',')
        let id = arr[0]
        let count = parseInt(arr[1])
        this.offsetTime = this.soldierData.trainTime * count
        let nextTime = event.eStartTime - Math.floor(UserInfo.instance.serverTime / 1000)
        this.offsetTime = this.offsetTime - this.soldierData.trainTime + nextTime
        this.trainNum.string = count + ''
        this.timeDown.string = Utils.secondToStr(this.offsetTime)


        if (this.offsetTime <= 0) {
            this.onClose()
            return
        }


        this.schedule(this.updateTime, 1, this.offsetTime - 1)
    }

    updateTime() {
        this.offsetTime--
        this.timeDown.string = `${Utils.secondToStr(this.offsetTime)}`

        if (this.offsetTime <= 0) {
            // 倒计时完成
            // 清除事件，刷新页面

            UserInfo.instance.refreshVillageDetail()
            this.onClose()
        }
    }

    onSlide(slider: Slider) {
        this._curTrainCount = Math.floor(slider.progress * this._maxCount)
        this.trainCount.string = this._curTrainCount + ''



    }

    async onComfrim() {
        if(this._curTrainCount == 0){
            UIManager.instance.tip('请设置训练数量')
            return
        }

        let index = this.soldierData.soldierIndex + 1
        let param = {
            ['t' + index]: this._curTrainCount
        }

        // 判断是在宫殿中，还是兵营中
        if (UIManager.instance.isOpenUI(PrefabEnum.TrainIndex)) {
            param.r = 1
        } else {
            param.r = 1
        }

        await UIManager.instance.showLoading()
        let res = await VillageApi.train(param)
        console.log('训练兵：', param, res)
        await UserInfo.instance.refreshVillageDetail()
        UIManager.instance.closeLoading()

        this.onClose()

        EventManager.instance.emit(EventManager.EventType.TrainSoldier, this.soldierData)

        this.refresh()
    }

    async onSpeed() {

        let event = this.soldierData.getTrainEvent()
        if (!event) {
            return
        }

        let param = {
            ac: EventOper.SPEED_BUILD,
            eid: event.eHandle
        }

        await UIManager.instance.showLoading()
        let res = await VillageApi.eventOper(param)
        UIManager.instance.closeLoading()
        console.log(`加速升级，ac =${param.ac} ,del =${param.eid} `, res)

        await UserInfo.instance.refreshVillageDetail()



        this.onClose()
    }

    async refresh() {
        let ui = await UIManager.instance.openUI(PrefabEnum.TrainNumber)
        ui.getComponent(TrainNumber).setData(this.soldierData)
    }

    onClose() {
        UIManager.instance.closeUI(PrefabEnum.TrainNumber)
    }

    async onPro() {
        let ui = await UIManager.instance.openUI(PrefabEnum.TrainProperty)
        ui.getComponent(TrainProperty).setData(this.soldierData)
    }

    async onDevelop() {
        let academy = BManager.getBManageById(buildingType.B22_Academy)
        if (!academy) {
            try {
                await UIManager.instance.confrim({
                    title: '提示',
                    content: '您还没有建造研究院',
                    confrimText: '去建造'
                })
                UIManager.instance.clear()
                UIManager.instance.openUI(PrefabEnum.BuildingList)
            } catch (error) {

            }
            return
        }
        UIManager.instance.clear()
        UIManager.instance.openUI(PrefabEnum.DevelopIndex)
    }
}


